package com.xixing.weixin.utils;

import org.apache.commons.lang3.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.HasParentFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Apple
 * Date: 13-4-9
 * Time: 下午2:33
 * To change this template use File | Settings | File Templates.
 */
public class HtmlParseUtils {

    public static String VIEW_STAT_START = "<input type=\"hidden\" name=\"__VIEWSTATE\" value=\"";
    public static String LIB_VIEW_STAT_START = "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"";
    public static String LIB_EVENT_VALITION_START = "<input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"";
    public static String VIEW_STAT_END = "\"";


    public static String findViewState(String html) {
        int startIndex = html.indexOf(VIEW_STAT_START) + VIEW_STAT_START.length();
        int endIndex = html.indexOf(VIEW_STAT_END, startIndex);


        return html.substring(startIndex, endIndex);
    }

    public static String findLibViewState(String html) {
        int startIndex = html.indexOf(LIB_VIEW_STAT_START) + LIB_VIEW_STAT_START.length();
        int endIndex = html.indexOf(VIEW_STAT_END, startIndex);


        return html.substring(startIndex, endIndex);
    }

    public static String findLibEventValition(String html) {
        int startIndex = html.indexOf(LIB_EVENT_VALITION_START) + LIB_EVENT_VALITION_START.length();
        int endIndex = html.indexOf(VIEW_STAT_END, startIndex);


        return html.substring(startIndex, endIndex);
    }

    /**
     * 根据id查找元素.
     *
     * @param html    HTML
     * @param charset 字符编码
     * @param id      ID
     * @return 元素
     */
    public static String findById(String html, String charset, String id) throws ParserException {
        Parser parser = Parser.createParser(html, charset);
        NodeList nodes = parser.extractAllNodesThatMatch(new HasAttributeFilter("id", id));
        if (nodes.size() == 0) return null;
        Node node = nodes.elementAt(0);
        return decode(node.toPlainTextString());
    }

    public static String findSelectValueById(String html, String charset, String id) throws ParserException {
        Parser parser1 = Parser.createParser(html, charset);
        NodeList nodes1 = parser1.extractAllNodesThatMatch(new AndFilter(new NodeFilter[]{
                new TagNameFilter("option"),
                new HasAttributeFilter("selected", "selected"),
                new HasParentFilter(new HasAttributeFilter("id", id))}));
        if (nodes1.size() == 0) return null;
        Node node = nodes1.elementAt(0);
        return decode(node.toPlainTextString());
    }

    public static List<Map<String, String>> findTableById(String html, String charset, String tableId, int[] cols) throws ParserException {
        List<Map<String, String>> result = new ArrayList<Map<String, String>>();

        Parser parser = Parser.createParser(html, charset);
        NodeList nodes = parser.extractAllNodesThatMatch(new HasAttributeFilter("id", tableId));
        if (nodes.size() == 0) return result;

        TableTag table = (TableTag) nodes.elementAt(0);
        TableRow[] rows = table.getRows();

        //取得表中的标题
        String[] titles = new String[cols.length];
        {
            TableRow tr = rows[0];

            for (int i = 0; i < cols.length; i++) {
                String text = getTableCell(tr, cols[i]);
                titles[i] = decode(text);
            }
        }

        //遍历每行
        for (int r = 1; r < rows.length; r++) {
            Map<String, String> row = new LinkedHashMap<String, String>();
            TableRow tr = rows[r];

            for (int i = 0; i < cols.length; i++) {
                String value = decode(getTableCell(tr, cols[i]));
                if (StringUtils.isNotBlank(value)) row.put(titles[i], value);
            }


            if (row.size() > 0) result.add(row);
        }

        return result;
    }

    private static String getTableCell(TableRow tr, int col) {
        TableColumn[] td = tr.getColumns();
        for (int i = 0, index = 0; i < td.length && index <= col; i++) {
            TableColumn tableColumn = td[i];
            if (col == index) return tableColumn.toPlainTextString();
            String colSpan = tableColumn.getAttribute("colSpan");
            if (colSpan != null && StringUtils.isNumeric(colSpan)) {
                index += Integer.parseInt(colSpan);
            } else {
                index++;
            }
        }

        return td[col].toPlainTextString();
    }

    public static String decode(String text) {
        if (text == null) return null;
        return text.replaceAll("&nbsp;", " ");
    }
}
